package com.ling.luo.config.ali;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Alipay {

    /**
     * 退款接口，支持部分退款
     * @param sn
     * @param refundSn
     * @param refundAmount
     * @param refundInfo
     * @return
     */
    public static String refund(String sn, String refundSn, String refundAmount, String refundInfo) {
        // 再次检查金额是否合法
        // 调用支付宝接口进行查看
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        Map<String, String> param = new HashMap<String, String>();
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        param.put("out_trade_no", sn);
        param.put("out_request_no", refundSn);
        param.put("refund_amount", refundAmount);
        param.put("refund_reason", refundInfo);

        alipayRequest.setBizContent(JSONObject.toJSONString(param));
        try {
            return alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

return null;
    }

    /**
     * 关闭订单接口
     * @param sn
     * @return
     */
    public static String closePay(String sn) {
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        // 设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
        Map<String, String> param = new HashMap<String, String>();
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        param.put("out_trade_no", sn);
        alipayRequest.setBizContent(JSONObject.toJSONString(param));
        // 请求
        try {
            return alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 支付宝pc端支付（拉起支付页面）
     * @param sn
     * @param totalAmout
     * @param title
     * @param info
     * @return
     */
    public static String AliPay(String sn, BigDecimal totalAmout, String title, String info) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Map param = new HashMap<String, String>();
        // 商户订单号
        param.put("out_trade_no", sn);
        // 付款金额
        param.put("total_amount", totalAmout);
        // 订单名称
        param.put("subject", title);
        // 商品描述 可空
        param.put("body", info);
        param.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //设置请求参数
        alipayRequest.setBizContent(JSONObject.toJSONString(param));

        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("*********************\n返回结果为："+result);
        return result;
    }


    /**
     * 验证支付宝异步通知签名是否合法
     * @param request
     * @return
     */
    public static boolean isValid(HttpServletRequest request) {
        /**
         * 验证签名合法原因：黑客模拟请求，把订单改为支付状态，则
         */
        Map params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr +values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决 这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
                params.put(name, valueStr);
                return AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            } catch (UnsupportedEncodingException | AlipayApiException e) {
                e.printStackTrace();
            }
        }

        return false;
    }
}
